<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="货物编码">
            <el-input v-model="formInline.cargoSn" placeholder="请输入货物编码" clearable />
          </el-form-item>
          <el-form-item label="货物名称">
            <el-input v-model="formInline.cargoName" placeholder="请输入货物名称" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="search">查找</el-button>
            <el-button type="primary" plain @click="add">新增</el-button>
            <el-button @click="init">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </template>

    <el-table :data="tableParams.rows" style="width: 100%">
      <el-table-column prop="cargoSn" label="货物编码" align="center" width="200" />
      <el-table-column prop="cargoName" label="货物名称" />
      <el-table-column prop="cargoWeight" label="重量（KG）" />
      <el-table-column prop="cargoVolume" label="体积(m³)" />
      <el-table-column prop="cargoUnit" label="单位">
        <template #default="scope">
          <selectUnit v-model="scope.row.cargoUnit" readonly="1"></selectUnit>
        </template>
      </el-table-column>
      <el-table-column prop="cargoSpec" label="规格" />
      <el-table-column prop="minStock" label="最低库存" />
      <el-table-column prop="maxStock" label="最高库存" />
      <el-table-column prop="earlyWarningDays" label="过期提前预警天数" />
      <el-table-column prop="remark" label="状态">
        <template #default="scope">
          <el-switch v-model="scope.row.status" @change="switchChange(scope.row)" inline-prompt active-text="启用" inactive-text="禁止" :active-value="0" :inactive-value="1" />
        </template>
      </el-table-column>
      <el-table-column label="操作" header-align="center" align="center" width="200">
        <template #default="scope">
          <el-button type="primary" text @click="handClick(scope.row,1)">编辑</el-button>
          <el-button type="primary" text @click="handClick(scope.row,2)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination v-if="tableParams['total']" :total="tableParams['total']" v-model:page="formInline.pageNum" v-model:limit="formInline.pageSize" @pagination="getInfo" />

    <el-dialog v-model="dialogVisible" title="新增/编辑货物 " width="800" :before-close="handleClose">
      <el-form :model="form" label-width="120" :rules="rules" ref="formEl" class="grids" label-position="top">
        <el-form-item label="货物编码" prop="cargoSn">
          <el-input v-model="form.cargoSn" placeholder="请输入货物编码" clearable disabled />
        </el-form-item>
        <el-form-item label="货物名称" prop="cargoName">
          <el-input v-model="form.cargoName" placeholder="请输入货物名称" clearable />
        </el-form-item>
        <el-form-item label="重量（KG）">
          <el-input v-model="form.cargoWeight" placeholder="请输入重量（KG）" clearable />
        </el-form-item>
        <el-form-item label="体积（m³）">
          <el-input v-model="form.cargoVolume" placeholder="请输入体积（m³）" clearable />
        </el-form-item>
        <el-form-item label="单位">
          <selectUnit v-model="form.cargoUnit"></selectUnit>
        </el-form-item>
        <el-form-item label="规格">
          <el-input v-model="form.cargoSpec" placeholder="请输入规格" clearable />
        </el-form-item>
        <el-form-item label="尺码">
          <el-input v-model="form.cargoSize" placeholder="请输入尺码" clearable />
        </el-form-item>
        <el-form-item label="最低库存">
          <el-input v-model="form.minStock" placeholder="请输入最低库存" clearable />
        </el-form-item>
        <el-form-item label="最高库存">
          <el-input v-model="form.maxStock" placeholder="请输入最高库存" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="form.status" inline-prompt active-text="启用" inactive-text="禁止" :active-value="0" :inactive-value="1" />
        </el-form-item>
        <el-form-item label="过期提前预警天数">
          <el-input v-model="form.earlyWarningDays" placeholder="请输入过期提前预警天数" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="submitForm" :loading="loading">
            确 认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { onMounted } from "vue";

const { proxy } = getCurrentInstance();
let formInline = ref({
  pageNum: 1,
  pageSize: 10,
  cargoSn: "",
  cargoName: "",
  status: null,
});
let tableParams = ref({});
let dialogVisible = ref(false);
let loading = ref(false);
let form = ref({
  cargoSn: "",
  cargoName: "",
  cargoWeight: "",
  cargoVolume: "",
  cargoUnit: "",
  cargoSpec: "",
  cargoSize: "",
  minStock: null,
  maxStock: null,
  earlyWarningDays: null,
  status: 0,
});
const validateSn = async (rule: any, value: any, callback: any) => {
  let canSet = false;
  if (value) {
    let { data } = await proxy.$apis.cargoCheckSn({
      id: form.value.id || "",
      supplierSn: value,
    });
    canSet = data;
  }
  if (!value) {
    callback(new Error("请输入编码"));
  } else if (!canSet) {
    callback(new Error("该编码已被使用"));
  } else {
    callback();
  }
};
let rules = ref({
  cargoSn: [
    {
      required: true,
      validator: validateSn,
      trigger: "blur",
    },
  ],
  cargoName: [
    {
      required: true,
      message: "货物名称",
      trigger: "blur",
    },
  ],
});

onMounted(() => {
  search();
});
let search = () => {
  formInline.value.pageNum = 1;
  getInfo();
};
let getInfo = async () => {
  tableParams.value = await proxy.$apis.cargoList(formInline.value);
};
let init = () => {
  formInline.value = {
    pageNum: 1,
    pageSize: 10,
    cargoSn: "",
    cargoName: "",
    status: null,
  };
  getInfo();
};
let handleClose = () => {
  form.value = {
    cargoSn: "",
    cargoName: "",
    cargoWeight: "",
    cargoVolume: "",
    cargoUnit: "",
    cargoSpec: "",
    cargoSize: "",
    minStock: null,
    maxStock: null,
    earlyWarningDays: null,
    status: 0,
  };
  proxy.$refs.formEl.resetFields();
  getInfo();
  dialogVisible.value = false;
};
let submitForm = async () => {
  await proxy.$refs.formEl.validate((valid, fields) => {
    if (valid) {
      save();
    } else {
      for (let key in fields) {
        return proxy.$utils.showToast(fields[key][0].message, 0);
      }
    }
  });
};
let save = async () => {
  try {
    loading.value = true;
    if (form.value.id) {
      await proxy.$apis.cargoEdit(form.value);
    } else {
      await proxy.$apis.cargoAdd(form.value);
    }
    proxy.$utils.showToast("操作成功");
    handleClose();
  } catch (error) {
  } finally {
    loading.value = false;
  }
};
let handClick = async (e: Object, index: Number) => {
  switch (index) {
    case 1:
      let { data } = await proxy.$apis.cargoDetails(e["id"]);
      form.value = proxy.$utils.formatFunction(data, { ...form.value });
      form.value.id = e["id"];
      dialogVisible.value = true;
      break;
    case 2:
      let resp = await proxy.$utils.confirmTips(
        `是否确定删除货物${e["cargoName"]}?`
      );
      if (!resp) return;
      await proxy.$apis.cargoDel(e["id"]);
      proxy.$utils.showToast("删除成功");
      getInfo();
      break;
    default:
      break;
  }
};
let switchChange = async (e: Object) => {
  form.value = proxy.$utils.formatFunction(e, { ...form.value });
  form.value.id = e["id"];
  await proxy.$apis.cargoEdit(form.value);
  proxy.$utils.showToast("操作成功");
  getInfo();
};
let add = async () => {
  form.value.cargoSn = `HW-${Date.now()}`;
  dialogVisible.value = true;
};
function findMaxId(arr, field) {
  return arr.reduce((maxObj, currentObj) => {
    if (currentObj[field] > maxObj[field]) {
      return currentObj;
    } else {
      return maxObj;
    }
  });
}
</script>

<style lang="scss" scoped>
.box-card {
  margin: 20px;
}
.grids {
  display: grid;
  grid-template-columns: repeat(2, minmax(0px, 1fr));
  gap: 8px 12px;
  grid-column-gap: 56rpx; //间隔
}
</style>
